package com.bwie.server;


import com.alibaba.fastjson.JSON;
import com.bwie.message.BaseMessage;
import com.bwie.message.ServerRespRegisterMessage;
import com.bwie.message.TerminalRegisterMessage;
import com.bwie.protocol.CustomProtocol;
import com.bwie.util.JT808Const;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务器端处理器
 */
public class TcpServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(TcpServerHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof CustomProtocol) {
            CustomProtocol protocol = (CustomProtocol) msg;
            String message = new String(protocol.getContent());
            logger.info("服务器收到消息: {}", message);

            //
            BaseMessage baseMessage = JSON.parseObject(message, BaseMessage.class);
            switch (baseMessage.getMessageId()) {
                case JT808Const.TERMINAL_MSG_REGISTER:
                    handleRegisterMessage(ctx, message);
                    break;
            }
//            ctx.writeAndFlush(new CustomProtocol("ok"));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("服务器发生异常", cause);
        ctx.close();
    }

    public void handleRegisterMessage(ChannelHandlerContext ctx, String message) {
        TerminalRegisterMessage terminalRegisterMessage = JSON.parseObject(message, TerminalRegisterMessage.class);
        logger.info("终端注册信息: {}", message);

        ServerRespRegisterMessage response = new ServerRespRegisterMessage();
        response.setResult((byte) 0);
        response.setAuthCode("12345");
        response.setFlowId((short)0);
        response.setReplyFlowId(terminalRegisterMessage.getFlowId());

        ctx.writeAndFlush(new CustomProtocol(JSON.toJSONString(response)));
    }
}

